package offer.zixing.chapter12;

import java.util.Random;

public class Test76_2 {
    public static void main(String[] args) {
        int[] arr = {7, 3, 2, 8, 1, 9, 5, 4, 6, 10};
        sort(arr, 0, arr.length - 1);
        print(arr);
    }

    public static void sort(int[] arr, int leftBound, int rightBound) {
        if (leftBound >= rightBound) {
            return;
        }
        int pivot = partition(arr, leftBound, rightBound);
        sort(arr, leftBound, pivot - 1);
        sort(arr, pivot +  1, rightBound);
    }

    private static int partition(int[] arr, int start, int end) {
        int pivot = new Random().nextInt(end - start + 1) + start;
        swap(arr, pivot, end);
        int small = start - 1;
        for (int i = start; i < end; i++) {
            if (arr[i] < arr[end]) {
                small++;
                swap(arr, i, small);
            }
        }
        small++;
        swap(arr, small, end);
        return small;
    }

    private static void swap(int[] nums, int index1, int index2) {
        if (nums[index1] != nums[index2]) {
            int temp = nums[index1];
            nums[index1] = nums[index2];
            nums[index2] = temp;
        }
    }

    static void print(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
